import { useCallback, useEffect, useState } from "react"
import SyntaxHighlighter from '@/components/SyntaxHighlighter'

const code1 = `
  <div className="third-container">
    <div className="column column1">
      { columns1.map((item) => 
        <img key={item} src={item} />
      ) }
    </div>
    <div className="column column2">
      { columns2.map((item) => 
        <img key={item} src={item} />
      ) }
    </div>
    <div className="column column3">
      { columns3.map((item) => 
        <img key={item} src={item} />
      ) }
    </div>
  </div>
  
  <style>
    .third-container {
      display: flex;
      gap: 8;
      .column {
        display: flex;
        flex-direction: column;
        flex: 1;
        gap: 8px;
      }
      img {
        width: calc(100% - 8px);
      }
    }
  </style>
`

function ThirdView({ listData }) {
  const [columns1, setColumns1] = useState([])
  const [columns2, setColumns2] = useState([])
  const [columns3, setColumns3] = useState([])

  const setData = useCallback(() => {
    const nums = Math.ceil(listData.length / 3)
      const arr1 = []
      const arr2 = []
      const arr3 = []
      for(let i = 0; i <= listData.length; i++) {
        if (i < nums) {
          arr1.push(listData[i])
          setColumns1(arr1)
        } else if (i < nums * 2) {
          arr2.push(listData[i])
          setColumns2(arr2)
        } else {
          arr3.push(listData[i])
          setColumns3(arr3)
        }
      }
  }, [listData])

  useEffect(() => {
    setData()
  }, [setData])

  return (
    <>
      <h3>flex布局</h3>
      <p>实现方式：将数据按照要求分成对应的列数，并按顺序依次放入对应列中，flex布局中渲染拆分成对应列数的容器，从上到下地排列元素</p>
      <p>方案特点：使用熟悉地flex布局，手动控制元素地渲染顺序，采用修改布局构造以及手动拆分数据的方式实现瀑布流</p>
      <p>实际应用：虽然能实现瀑布流效果，但是仅按照各列元素个数进行平分，并不能智能计算各列的高度对空白进行补充</p>

      <SyntaxHighlighter children={code1} language="html" />

      <div className="third-container">
        <div className="column column1">
          { columns1.map((item) => 
            <img key={item} src={item} />
          ) }
        </div>
        <div className="column column2">
          { columns2.map((item) => 
            <img key={item} src={item} />
          ) }
        </div>
        <div className="column column3">
          { columns3.map((item) => 
            <img key={item} src={item} />
          ) }
        </div>
      </div>
    </>
  )
}

export default ThirdView